package org.example;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.time.LocalDate;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CA {
    private static final Logger LOGGER = Logger.getLogger(CA.class);

    private static final String MY_NAME = "CA_ROOT";
    private static final PrivateKey PRIVATE_KEY;
    public static final PublicKey PUBLIC_KEY;

    static {
        // 生成CA的公私密钥
        KeyPair keyPair = SecretKeyUtil.createRSAKey();
        PRIVATE_KEY = keyPair.getPrivate();
        PUBLIC_KEY = keyPair.getPublic();
    }

    /**
     * 颁发证书
     * @return
     */
    public static Certificate issueCertificate(String organization, String domainName, PublicKey publicKey) {
        Certificate certificate = new Certificate(
                randomSerialNumber(), LocalDate.now().plusYears(1L),
                organization, domainName,
                publicKey, MY_NAME
        );
        certificate.setSign(SecretKeyUtil.encryptRSA(PRIVATE_KEY, certificate.calDigest().getBytes(StandardCharsets.UTF_8)));
        LOGGER.info(String.format("为[%s][domain=%s]颁发证书完成", organization, domainName));
        LOGGER.info(String.format("证书内容为[%s]", certificate));
        return certificate;
    }

    private static String randomSerialNumber() {
        Random random = new Random();
        return Stream.generate(() -> random.nextInt(100)).limit(10).map(String::valueOf).collect(Collectors.joining(":"));
    }
}
